from fastapi import FastAPI
from tortoise.contrib.fastapi import register_tortoise
from .database import connect_db, disconnect_db
from .admin import configure_admin, create_admin_user
from fastapi_admin.app import app as admin_app
from tortoise_config import TORTOISE_ORM

import logging
#设置定时任务模块日志的输出级别,否则会被刷屏
logging.getLogger('apscheduler').setLevel(logging.WARNING)
from .mylogging import setup_logging
setup_logging()
logger = logging.getLogger(__name__)
from .back_groundScheduler import start_scheduler,shutdown_scheduler


app = FastAPI()

# 注册用户路由
from .user.routes import router as user_router
app.include_router(user_router, prefix="/user", tags=["User"])
from .tactics.routes import router as tactics_router
app.include_router(tactics_router, prefix="/tactics", tags=["Tactics"])


@app.on_event("startup")
async def startup():
    # 连接数据库
    await connect_db()
    # 配置 FastAPI Admin
    await configure_admin()
    await create_admin_user()
    logger.info("FASTAPI startup")
    # 启动调度器
    start_scheduler()
    logger.info("scheduler startup")

@app.on_event("shutdown")
async def shutdown():
    #关闭调度器
    shutdown_scheduler()
    # 断开数据库连接
    await disconnect_db()
    # 关闭 FastAPI Admin
    await admin_app.shutdown()


# 注册 Tortoise ORM
register_tortoise(
    app,
    config=TORTOISE_ORM,
    #是否自动将model的表结构更新给数据库,正式环境不建议开启
    generate_schemas=True,
    add_exception_handlers=True,
)

app.mount("/admin", admin_app)
